<template>
  <div class="environment-monitor">
    <div class="section-title">
      <el-icon><Sunrise /></el-icon>
      智慧大棚实时环境监测
    </div>
    <div class="gauge-container">
      <el-card class="gauge-item" shadow="never">
        <div class="gauge-title">
          <el-icon><Histogram /></el-icon>
          空气温度
        </div>
        <div ref="tempGauge" class="gauge-chart"></div>
        <div class="gauge-value">28.4 °C</div>
      </el-card>
      <el-card class="gauge-item" shadow="never">
        <div class="gauge-title">
          <el-icon><Cloudy /></el-icon>
          空气湿度
        </div>
        <div ref="humidityGauge" class="gauge-chart"></div>
        <div class="gauge-value">61.4 %RH</div>
      </el-card>
    </div>
    <div class="section-title" style="margin-top: 0px;">
      <el-icon><DataLine /></el-icon>
      温度监测数据统计
    </div>
    <el-card class="chart-container" shadow="never">
      <div ref="trendChart" class="trend-chart"></div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { Sunrise, Histogram, Cloudy, DataLine } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { getSoilTemperatureData, getPhData } from '@/api'

const tempGauge = ref(null)
const humidityGauge = ref(null)
const trendChart = ref(null)
const charts = ref([])

// 实时数据
const temperature = ref(0)
const humidity = ref(0)

// 格式化日期为时间戳
const formatDate = (date) => {
  return Math.floor(date.getTime())
}

// 获取实时数据
const fetchRealTimeData = async () => {
  try {
    const now = new Date()
    const fiveMinutesAgo = new Date(now - 5 * 60 * 1000)
    
    const [tempData, phData] = await Promise.all([
      getSoilTemperatureData(formatDate(fiveMinutesAgo), formatDate(now)),
      getPhData(formatDate(fiveMinutesAgo), formatDate(now))
    ])
    
    // 使用最新的数据点
    if (tempData.length > 0) {
      temperature.value = tempData[tempData.length - 1].value
    }
    if (phData.length > 0) {
      humidity.value = phData[phData.length - 1].value
    }
    
    // 更新仪表盘
    updateGauges()
  } catch (error) {
    console.error('获取实时数据失败:', error)
  }
}

// 获取历史数据
const fetchHistoryData = async () => {
  try {
    // 获取过去24小时的数据
    const endTime = new Date()
    const startTime = new Date(endTime - 24 * 60 * 60 * 1000)
    
    const [tempHistory, phHistory] = await Promise.all([
      getSoilTemperatureData(formatDate(startTime), formatDate(endTime)),
      getPhData(formatDate(startTime), formatDate(endTime))
    ])
    
    // 更新趋势图
    updateTrendChart(tempHistory, phHistory)
  } catch (error) {
    console.error('获取历史数据失败:', error)
  }
}

// 初始化仪表盘
const initGauges = () => {
  if (!tempGauge.value || !humidityGauge.value) return
  
  const tempChart = echarts.init(tempGauge.value)
  const humidityChart = echarts.init(humidityGauge.value)
  
  const gaugeOption = {
    series: [{
      type: 'gauge',
      startAngle: 225,
      endAngle: -45,
      min: 0,
      max: 100,
      splitNumber: 10,
      axisLine: {
        lineStyle: {
          width: 6,
          color: [
            [0.3, '#67e0e3'],
            [0.7, '#37a2da'],
            [1, '#fd666d']
          ]
        }
      },
      pointer: {
        itemStyle: {
          color: 'auto'
        }
      },
      axisTick: {
        distance: -20,
        length: 8,
        lineStyle: {
          color: '#fff',
          width: 2
        }
      },
      splitLine: {
        distance: -20,
        length: 30,
        lineStyle: {
          color: '#fff',
          width: 2
        }
      },
      axisLabel: {
        color: '#fff',
        distance: -30,
        fontSize: 10
      },
      detail: {
        valueAnimation: true,
        formatter: '{value}',
        color: '#fff',
        fontSize: 14
      },
      data: [{
        value: 0
      }]
    }]
  }
  
  tempChart.setOption(gaugeOption)
  humidityChart.setOption(gaugeOption)
  
  charts.value.push(tempChart, humidityChart)
}

// 更新仪表盘数据
const updateGauges = () => {
  if (charts.value.length >= 2) {
    charts.value[0].setOption({
      series: [{
        data: [{
          value: temperature.value
        }]
      }]
    })
    charts.value[1].setOption({
      series: [{
        data: [{
          value: humidity.value
        }]
      }]
    })
  }
}

// 初始化趋势图
const initTrendChart = () => {
  if (!trendChart.value) return
  
  const chart = echarts.init(trendChart.value)
  charts.value.push(chart)
  
  const option = {
    backgroundColor: 'transparent',
    grid: {
      top: 40,
      left: 50,
      right: 40,
      bottom: 30
    },
    legend: {
      data: ['温度', '湿度'],
      textStyle: {
        color: '#fff'
      }
    },
    xAxis: {
      type: 'time',
      axisLine: {
        lineStyle: {
          color: '#fff'
        }
      },
      axisLabel: {
        color: '#fff'
      }
    },
    yAxis: {
      type: 'value',
      axisLine: {
        lineStyle: {
          color: '#fff'
        }
      },
      axisLabel: {
        color: '#fff'
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(255,255,255,0.1)'
        }
      }
    },
    series: [
      {
        name: '温度',
        type: 'line',
        smooth: true,
        symbol: 'none',
        data: []
      },
      {
        name: '湿度',
        type: 'line',
        smooth: true,
        symbol: 'none',
        data: []
      }
    ]
  }
  
  chart.setOption(option)
}

// 更新趋势图数据
const updateTrendChart = (tempData, humidityData) => {
  if (charts.value.length < 3) return
  
  const formatData = (data) => {
    return data.map(item => [new Date(item.timestamp).getTime(), item.value])
  }
  
  charts.value[2].setOption({
    series: [
      { data: formatData(tempData) },
      { data: formatData(humidityData) }
    ]
  })
}

onMounted(() => {
  initGauges()
  initTrendChart()
  fetchRealTimeData()
  fetchHistoryData()
  
  // 每5分钟更新一次实时数据
  const realTimeTimer = setInterval(fetchRealTimeData, 5 * 60 * 1000)
  // 每小时更新一次历史数据
  const historyTimer = setInterval(fetchHistoryData, 60 * 60 * 1000)
  
  onUnmounted(() => {
    clearInterval(realTimeTimer)
    clearInterval(historyTimer)
    charts.value.forEach(chart => {
      chart.dispose()
    })
    charts.value = []
  })
})
</script>

<style scoped>
.environment-monitor {
  background: rgba(0, 21, 41, 0.7);
  border: 1px solid rgba(0, 222, 255, 0.3);
  border-radius: 8px;
  padding: 16px;
  flex: 1;
  display: flex;
  flex-direction: column;
  backdrop-filter: blur(10px);
  box-sizing: border-box;
  min-height: 400px;
  height: 100%;
}

.section-title {
  color: #00deff;
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 12px;
  text-shadow: 0 0 10px rgba(0, 222, 255, 0.3);
  letter-spacing: 1px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.gauge-container {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  gap: 12px;
  height: 120px;
  width: 100%;
}

.gauge-item {
  flex: 1;
  max-width: 160px;
  background: rgba(0, 21, 41, 0.5);
  border: 1px solid rgba(0, 222, 255, 0.2);
  border-radius: 6px;
  padding: 2px 10px 6px;
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
}

.gauge-chart {
  flex: 1;
  width: 100%;
  min-height: 70px;
  margin-bottom: 4px;
}

.trend-container {
  flex: 1;
  background: rgba(0, 21, 41, 0.5);
  border: 1px solid rgba(0, 222, 255, 0.2);
  border-radius: 6px;
  padding: 12px;
  min-height: 180px;
  display: flex;
  flex-direction: column;
  margin-top: auto;
}

.gauge-title {
  color: rgba(255, 255, 255, 0.9);
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 2px;
  display: flex;
  align-items: center;
  gap: 4px;
  margin-top: -2px;
}

.gauge-title .el-icon {
  font-size: 16px;
  color: #00deff;
}

.gauge-value {
  color: #00deff;
  font-size: 18px;
  font-weight: bold;
  margin-top: 0px;
  text-align: center;
}

:deep(.chart-container) {
  flex: 1;
  background: rgba(0, 21, 41, 0.5) !important;
  border: 1px solid rgba(0, 222, 255, 0.2) !important;
  border-radius: 6px !important;
  min-height: 0;
  transition: all 0.3s ease;
}

:deep(.chart-container:hover) {
  border-color: rgba(0, 222, 255, 0.4) !important;
  box-shadow: 0 0 15px rgba(0, 222, 255, 0.1);
}

:deep(.chart-container .el-card__body) {
  height: 100%;
  padding: 12px;
  display: flex;
}

.trend-chart {
  flex: 1;
  width: 100%;
  min-height: 160px;
}
</style> 